package com.jams.goodox.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jams.goodox.BaseFragment;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.qa.entity.Question;
import com.jams.goodox.activity.teacher.TeacherQuestionAnswerDetailActivity;
import com.jams.goodox.adapter.lfadapter.QaFragmentAdapter;
import com.jams.goodox.net.ProtocolManagers;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.widget.CustomPopWindow;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.leefeng.lfrecyclerview.LFRecyclerView;
import me.leefeng.lfrecyclerview.OnItemClickListener;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 问答页面
 * @author HP
 */

public class TeacherQAFragment extends BaseFragment implements OnItemClickListener,
        LFRecyclerView.LFRecyclerViewListener {

    private static final String TAG = "TeacherQAFragment";

    View rootView;

    @Bind(R.id.unlogin_show)
    LinearLayout unlogin_show;

    @Bind(R.id.recycleView)
    LFRecyclerView recycleView;

    @Bind(R.id.grid_type)
    TextView grid_type;

    CustomPopWindow popWindow;

    private List<Question> qaBeanList =new ArrayList<>();
//    private List<Question> unBeanList =new ArrayList<>();
//    private List<Question> anBeanList =new ArrayList<>();

    private QaFragmentAdapter pAdapter;

    private Intent intent;

    private boolean status = false;//判断加载成功还是失败

    private boolean isRefresh = true;
    private int pageNum = 1;

    int section = 2;//问答状态(0未回答，1已回答，2 所有)

    Handler handler = new Handler(){
        @Override
        public void dispatchMessage(Message msg) {
            if(msg.what == 1){
                if (isRefresh){
                    recycleView.stopRefresh(status);
                    pAdapter.notifyDataSetChanged();
                }else {
                    recycleView.stopLoadMore();
                    pAdapter.notifyDataSetChanged();
                }
            }
        }
    };


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.qa_fragment, container, false);
            // 初始化页面
            ButterKnife.bind(this, rootView);
        }
        ButterKnife.bind(this, rootView);

        init();
        return rootView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getData();
    }

    private void init() {
        grid_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPoP(v);
            }
        });

        pAdapter = new QaFragmentAdapter(getActivity(),qaBeanList);
        recycleView.setFootText("---我是有底线的---");

        recycleView.setLoadMore(true);
        recycleView.setRefresh(true);
        recycleView.setNoDateShow();
        recycleView.setAutoLoadMore(false);
        recycleView.setOnItemClickListener(this);
        recycleView.setLFRecyclerViewListener(this);
        //recyclerView.setScrollChangeListener(this);
        recycleView.setItemAnimator(new DefaultItemAnimator());

        recycleView.setAdapter(pAdapter);
    }

    private void showPoP(View view) {

        //创建并显示popWindow
        if(null == popWindow){
            View viewPop = LayoutInflater.from(getContext()).inflate(R.layout.pop_layout1,null);
            popWindow = new CustomPopWindow.PopupWindowBuilder(getContext())
                    .setView(viewPop)
                    .setFocusable(true)
                    .setOutsideTouchable(true)
                    .create();

            viewPop.findViewById(R.id.all).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popWindow.dissmiss();
                    section = 2;
                    getData();
                    grid_type.setText("全部");
                    //pAdapter.setData(qaBeanList);
                }
            });

            viewPop.findViewById(R.id.yihuida).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popWindow.dissmiss();
                    section = 1;
                    getData();//已回答
                    grid_type.setText("已回答");
                    //pAdapter.setData(anBeanList);
                }
            });


            viewPop.findViewById(R.id.weihuida).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popWindow.dissmiss();
                    section = 0;
                    getData();//未回答
                    grid_type.setText("未回答");
                    //pAdapter.setData(unBeanList);
                }
            });
        }

        popWindow.showAsDropDown(view,0,10);

    }


    //我的问答接口
    private void getData(){
        clearMap();

        StringBuilder pData = new StringBuilder();
        pData.append("\"memberId\":" + SePref.getId())
                .append(",\"pageNum\":" + pageNum)
                .append(",\"pageSize\":" + 20);

        params.put("requestData", "{" + pData.toString() + "}");

        String strEntity = gson.toJson(params);

        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"),strEntity);

        showLoading();
        Call<ResponseBody> example;
        if(section == 0){
            example = createCallService(LoginService.class).teacherAsk(body);
        }else if(section == 0){
            example = createCallService(LoginService.class).teacherAnswered(body);
        }else {
            example = createCallService(LoginService.class).teacherQA(body);
        }

        example.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code")){
                        status = true;
                        Log.d(TAG,"responseData == " + jsonObject.getString("responseData"));
                        JSONArray jsonArray = new JSONArray(jsonObject.getString("responseData"));

                        if(isRefresh){
                            qaBeanList.clear();
                            //pAdapter.notifyDataSetChanged();
                        }
                        for (int i = 0; i < jsonArray.length(); i ++){
                            JSONObject object = jsonArray.getJSONObject(i);
                            //问答状态(0未回答，1已回答，2已查看答案)

                                Question question = new Question();
                                question.setId(object.getInt("id"));
                                question.setCreateTime(object.getLong("createTime"));
                                question.setNickName(object.getString("nickName"));
                                question.setImgPath(object.getString("imgPath"));
                                question.setQueState(object.getInt("queState"));
                                question.setDescr(object.getString("descr"));
                                question.setType(1);
                                qaBeanList.add(question);

//                            if(section == 2){
//                                Question question = new Question();
//                                question.setId(object.getInt("id"));
//                                question.setCreateTime(object.getLong("createTime"));
//                                question.setNickName(object.getString("nickName"));
//                                question.setImgPath(object.getString("imgPath"));
//                                question.setQueState(object.getInt("queState"));
//                                question.setDescr(object.getString("descr"));
//                                question.setType(1);
//                                qaBeanList.add(question);
//                            }else {
//                                if(object.getInt("queState") == section){
//                                    Question question = new Question();
//                                    question.setId(object.getInt("id"));
//                                    question.setCreateTime(object.getLong("createTime"));
//                                    question.setNickName(object.getString("nickName"));
//                                    question.setImgPath(object.getString("imgPath"));
//                                    question.setQueState(object.getInt("queState"));
//                                    question.setDescr(object.getString("descr"));
//                                    question.setType(1);
//                                    qaBeanList.add(question);
//                                }
//                            }
                        }

                    }else {
                        status = false;
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }
                } catch (Exception e) {
                    ToastUtil.show("Exception:" + e.getMessage());
                }

                handler.sendEmptyMessage(1);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                status = false;
                handler.sendEmptyMessage(1);
                Log.d(TAG,"onFailure = " + t.getMessage());
            }
        });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG,"onResume = " );
        if (!SePref.isLogin()){
            grid_type.setVisibility(View.GONE);
            unlogin_show.setVisibility(View.VISIBLE);
            recycleView.setVisibility(View.GONE);
        }else {
            grid_type.setVisibility(View.VISIBLE);
            unlogin_show.setVisibility(View.GONE);
            recycleView.setVisibility(View.VISIBLE);
//            qaBeanList.clear();
//            unBeanList.clear();
//            anBeanList.clear();
            grid_type.setText("全部");
            getData();
        }

        section = 2;
        getData();
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        pageNum = 1;
        section = 0;
        getData();
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        isRefresh = false;
        getData();
    }

    @Override
    public void onClick(int position) {
        Log.d(TAG," == " + qaBeanList.get(position).isAnswer());
        intent = new Intent(getActivity(),TeacherQuestionAnswerDetailActivity.class);
//        intent.putExtra("questionId",question.getId());
//        intent.putExtra("isAnswer",question.isAnswer());
        intent.putExtra("question",qaBeanList.get(position));
        startActivity(intent);
    }

    @Override
    public void onLongClick(int po) {

    }
}
